package org.pt.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.pt.components.Response;
import org.pt.dto.UserAdminDto;
import org.pt.dto.UserInfoDto;
import org.pt.exception.CheatAnalysisException;
import org.pt.exception.DBNotFoundExcepton;
import org.pt.exception.UserException;
import org.pt.exception.WorkException;
import org.pt.model.CheatAnalysisResult;
import org.pt.model.Post;
import org.pt.model.Work;
import org.pt.service.impl.AdminServiceImpl;
import org.pt.service.impl.PostServiceImpl;
import org.pt.utils.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminServiceImpl adminServiceImpl;

    @Autowired
    private PostServiceImpl postService;

    @GetMapping("bootCheatAnalysis")
    public Response<String> bootCheatAnalysis(@RequestHeader("Authorization") String token) throws UserException, CheatAnalysisException {
        return adminServiceImpl.bootCheatAnalysis(token);
    }

    @GetMapping("getUserAdminList")
    public Response<List<UserAdminDto>> getUserAdminList(@RequestHeader("Authorization") String token, @RequestParam int pageNum, @RequestParam int pageSize) throws UserException, CheatAnalysisException {
        return adminServiceImpl.getUserAdminList(token, pageNum, pageSize);
    }

    @GetMapping("getAnalysisResult")
    public Response<CheatAnalysisResult> getAnalysisResult(@RequestHeader("Authorization") String token, @RequestParam int userId) throws UserException {
        return adminServiceImpl.getAnalysisResult(token, userId);
    }

    @PostMapping("banned")
    public Response<String> banned(@RequestHeader("Authorization") String token, @RequestParam int userId) throws UserException, CheatAnalysisException {
        return adminServiceImpl.banned(token, userId);
    }

    @PostMapping("unbanned")
    public Response<String> unbanned(@RequestHeader("Authorization") String token, @RequestParam int userId) throws UserException, CheatAnalysisException {
        return adminServiceImpl.unbanned(token, userId);
    }

    @PostMapping("delete_work")
    public Response<String> deleteByAdmin(@RequestHeader("Authorization") String token,
                                          @RequestParam Integer workId) throws UserException {

        return adminServiceImpl.adminDeleteWork(token, workId);
    }

    @PostMapping("set_on_sale")
    public Response<Work> setWorkOnSale(@RequestHeader("Authorization") String token,
                                        @RequestParam Integer workId,
                                        @RequestParam boolean onSale,
                                        @RequestParam float netRate,
                                        @RequestParam float costRate) throws WorkException, UserException, DBNotFoundExcepton {
        return adminServiceImpl.setWorkOnSale(token, workId, onSale, netRate, costRate);

    }

    @GetMapping("get_all_works")
    public Response<Page<Work>> getAllWorksByAdmin(@RequestHeader("Authorization") String token,
                                                   @RequestParam int pageNum,
                                                   @RequestParam int pageSize) throws UserException, CheatAnalysisException {

        return adminServiceImpl.getAllWorks(token,pageNum, pageSize);
    }

    // ==================== 帖子管理功能 ====================

    @Operation(
            summary = "管理员查看所有帖子",
            description = "管理员权限：获取所有帖子列表，按置顶优先、创建时间倒序排列"
    )
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200",
                    description = "查询成功",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Response.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "权限不足，非管理员用户",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Response.class)
                    )
            )
    })
    @GetMapping("/post/getAllPosts")
    public Response<List<Post>> getAllPosts(
            @Parameter(
                    name = "Authorization",
                    description = "管理员认证token",
                    required = true,
                    in = ParameterIn.HEADER,
                    example = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
            )
            @RequestHeader("Authorization") String token) throws UserException {

        // 验证管理员权限
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("权限不足，需要管理员权限");
        }

        return postService.getAllPosts();
    }

    @Operation(
            summary = "管理员置顶帖子",
            description = "管理员权限：将指定帖子设置为置顶状态"
    )
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200",
                    description = "置顶成功",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Response.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "404",
                    description = "帖子不存在",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Response.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "权限不足，非管理员用户",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Response.class)
                    )
            )
    })
    @PostMapping("/post/stickyPost")
    public Response<String> stickyPost(
            @Parameter(
                    name = "Authorization",
                    description = "管理员认证token",
                    required = true,
                    in = ParameterIn.HEADER,
                    example = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
            )
            @RequestHeader("Authorization") String token,
            @Parameter(
                    name = "postId",
                    description = "要置顶的帖子ID",
                    required = true,
                    example = "1"
            )
            @RequestParam Long postId) throws UserException {

        // 验证管理员权限
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("权限不足，需要管理员权限");
        }

        return postService.stickyPost(postId);
    }

    @Operation(
            summary = "管理员取消帖子置顶",
            description = "管理员权限：取消指定帖子的置顶状态"
    )
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200",
                    description = "取消置顶成功",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Response.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "404",
                    description = "帖子不存在",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Response.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "权限不足，非管理员用户",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Response.class)
                    )
            )
    })
    @PostMapping("/post/unstickyPost")
    public Response<String> unstickyPost(
            @Parameter(
                    name = "Authorization",
                    description = "管理员认证token",
                    required = true,
                    in = ParameterIn.HEADER,
                    example = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
            )
            @RequestHeader("Authorization") String token,
            @Parameter(
                    name = "postId",
                    description = "要取消置顶的帖子ID",
                    required = true,
                    example = "1"
            )
            @RequestParam Long postId) throws UserException {

        // 验证管理员权限
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("权限不足，需要管理员权限");
        }

        return postService.unstickyPost(postId);
    }

    @Operation(
            summary = "管理员删除帖子",
            description = "管理员权限：删除指定的帖子"
    )
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200",
                    description = "删除成功",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Response.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "404",
                    description = "帖子不存在",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Response.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "权限不足，非管理员用户",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Response.class)
                    )
            )
    })
    @DeleteMapping("/post/deletePost")
    public Response<String> deletePost(
            @Parameter(
                    name = "Authorization",
                    description = "管理员认证token",
                    required = true,
                    in = ParameterIn.HEADER,
                    example = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
            )
            @RequestHeader("Authorization") String token,
            @Parameter(
                    name = "postId",
                    description = "要删除的帖子ID",
                    required = true,
                    example = "1"
            )
            @RequestParam Long postId) throws UserException {

        // 验证管理员权限
        boolean isAdmin = JwtToken.isAdmin(token);
        if (!isAdmin) {
            throw new UserException("权限不足，需要管理员权限");
        }

        return postService.deletePost(postId);
    }
}
